package com.wg.leetcode;

public class Solution {
    public static void main(String[] args) {
        String[] params = {"ab", "a"};
        long startTime = System.nanoTime();
        System.out.println(longestCommonPrefix(params));
        long endTime = System.nanoTime();
        System.out.println("耗时：" + (endTime - startTime));
        startTime = System.nanoTime();
        System.out.println(longestCommonPrefix_2(params));
        endTime = System.nanoTime();
        System.out.println("耗时：" + (endTime - startTime));
    }

    /**
     * 最长公共前缀
     * 1.横向方法取两个字符串公共前缀与剩下的一个比较
     *
     * @param params
     */
    public static String longestCommonPrefix(String params[]) {
        //1.横向方法取两个字符串公共前缀与剩下的一个比较
        String commonChars = params[0];
        for (int i = 1; i < params.length; i++) {
            int index = 0;
            while (index < commonChars.length() && index < params[i].length() && commonChars.charAt(index) == params[i]
                .charAt(index)) {
                index++;
            }
            commonChars = commonChars.substring(0, index);
        }
        return commonChars;
    }

    /**
     * 最长公共前缀
     * 2.纵向方法
     *
     * @param strs
     */
    public static String longestCommonPrefix_2(String strs[]) {
        if (strs == null || strs.length == 0) {
            return "";
        }
        int index = 0;
        for (int i = 0; i < strs[0].length(); i++) {
            for (int j = 1; j < strs.length; j++) {
                if (i >= strs[j].length()) {
                    return strs[0].substring(0, i);
                } else if (strs[0].charAt(i) != strs[j].charAt(i)) {
                    return strs[0].substring(0, i);
                }
            }
        }
        return strs[0];
    }
}
